import pytest
from pathlib import Path
from datetime import datetime
import os
import sys
import argparse

# 将src目录添加到系统路径
sys.path.append(str(Path(__file__).parent.parent / "src"))

def get_test_files(mode: str = None):
    """根据模式获取测试文件"""
    if mode == "cmp":
        return ["tests/functional/test_CMP.py"]
    elif mode == "regular":
        return ["tests/functional/test_regular.py"]
    else:
        return ["tests/functional/test_registration_patterns.py"]

def main():
    """主函数，执行测试并生成定制化报告"""
    parser = argparse.ArgumentParser(description='执行专业注册测试')
    parser.add_argument('--mode', choices=['all', 'cmp', 'regular'], default='all',
                       help='测试模式: all(默认)/cmp(仅中药师)/regular(非中药师)')
    args = parser.parse_args()
    
    # 创建artifacts和reports目录
    artifacts_dir = Path(__file__).parent / "artifacts"
    reports_dir = artifacts_dir / "reports"
    reports_dir.mkdir(parents=True, exist_ok=True)
    
    # 设置报告路径
    current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
    test_file = "professional_cmp" if args.mode == "cmp" else "regular" if args.mode == "regular" else "all"
    os.environ["TEST_FILE"] = test_file
    # report_path = reports_dir / f"report_{test_file}_{current_time}.html"
    
    # 获取测试文件路径
    test_paths = get_test_files(args.mode)
    
    # 设置环境变量
    template_path = str(Path(__file__).parent.parent / "src" / "utils" / "reporting.py")
    os.environ["PYTEST_HTML_TEMPLATE"] = template_path
    # os.environ["REPORT_PATH"] = str(report_path)  # 设置报告路径环境变量

    # 配置pytest参数
    pytest_args = [
        "-v",
        # "--html", str(report_path),
        "--self-contained-html",
        "--no-header",
        "--no-summary",
        "--tb=no",
        "--capture=no",
        *test_paths
    ]

    # 记录开始时间
    start_time = datetime.now()
    
    # 执行测试
    exit_code = pytest.main(pytest_args)
    
    # 计算测试时长
    end_time = datetime.now()
    duration = end_time - start_time
    
    # 处理执行结果
    if exit_code == pytest.ExitCode.NO_TESTS_COLLECTED:
        print("\n错误：未收集到任何测试用例！请检查：")
        print("1. professional_patterns.json 文件是否存在且格式正确")
        print("2. 测试文件路径是否正确")
        print("3. 测试类和方法命名是否符合规范")
    else:
        print(f"\n测试执行完成，总耗时: {duration}")
        
        # 删除pytest生成的默认报告
        default_report = Path("artifacts/reports/pytest_report.html")
        if default_report.exists():
            default_report.unlink()

if __name__ == "__main__":
    main()